package top.changelife.learn.springmvc.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用 HTTP 协议实现的 Servlet 的基类：
 * 主要重写了 service 方法，在 service 方法中首先将 ServletRequest 和 ServletResponse 转换为 HttpServletRequest 和 HttpServletResponse
 * 然后根据 HTTP 请求的类型不同将请求路由到了不同的处理方法
 *
 * @author cz
 * @date 2019/12/24 14:11
 */
public class HttpServletInfo extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
        HttpServletRequest request;
        HttpServletResponse response;
        // 如果请求类型不相符，则抛出异常
        if (!(req instanceof HttpServletRequest &&
                res instanceof HttpServletResponse)) {
            throw new ServletException("non-HTTP request or response");
        }
        // 转换 request 和 response 的类型
        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;
        // 调用 http 的处理方法
        service(request, response);
    }
}
